package com.ft.adbix.utils.data.gather.util;

import android.Manifest;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;

import com.ft.adbix.oaid.OAIDManager;
import com.ft.adbix.oaid.util.OAIDUtils;
import com.ft.adbix.utils.AdLogUtils;
import com.ft.adbix.utils.WxSupportChecker;
import com.ft.adbix.utils.data.gather.common.DataGatherManager;
import com.ft.adbix.utils.data.gather.constant.Constant;
import com.ft.adbix.utils.data.gather.entity.CustomPhoneState;
import com.ft.adbix.utils.data.gather.listener.DeviceDataGatherListener;
import com.ft.adbix.utils.data.gather.manager.DatagatherOaidManager;
import com.ft.adbix.utils.data.gather.util.device.BatteryUtil;
import com.ft.adbix.utils.data.gather.util.device.BlueToothUtil;
import com.ft.adbix.utils.data.gather.util.device.CpuUtil;
import com.ft.adbix.utils.data.gather.util.device.DisplayUtil;
import com.ft.adbix.utils.data.gather.util.device.NetworkUtil;
import com.ft.adbix.utils.data.gather.util.device.PhoneStateUtil;
import com.ft.adbix.utils.data.gather.util.device.SystemClockUtil;
import com.ft.adbix.utils.data.synchronize.entity.CustomBluetoothInfo;
import com.ft.adbix.utils.data.synchronize.entity.DeviceData;
import com.ft.adbix.utils.data.synchronize.manager.DataCacheManager;
import com.ft.adbix.utils.data.synchronize.util.TimeUtil;
import com.ft.adbix.utils.http.manager.AsyncThreadPoolManager;
import com.ft.adbix.utils.permission.PermissionUtils;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;

public class DataGatherUtil {

    private static String[] localAppList;
    private static long lastLoadAppListTime;
    public static DeviceData currentDeviceData;

    /**
     * 手机设备信息
     *
     * @param deviceDataGatherListener ：设备信息收集监听
     */
    public static void gatherDeviceData(final DeviceDataGatherListener deviceDataGatherListener) {
        if (deviceDataGatherListener == null) {
            return;
        }
        gatherDeviceData(Constant.GET_DATA_NULL, deviceDataGatherListener);
    }

    private static void gatherDeviceData(final String signalStrength, final DeviceDataGatherListener deviceDataGatherListener) {
        if (currentDeviceData == null) {
            currentDeviceData = new DeviceData();
        }
        gatherLocationAndStationData(currentDeviceData);
        AsyncThreadPoolManager.getInstance().getThreadPool().execute(new Runnable() {
            @Override
            public void run() {
                currentDeviceData.setOs(1);
                gatherDisplayData(currentDeviceData);

                gatherNetworkData(currentDeviceData);

                gatherPhoneStateData(currentDeviceData);


                gatherBatteryData(currentDeviceData);

                gatherCpuData(currentDeviceData);

                gatherBluetoothData(currentDeviceData);

                gatherOtherData(currentDeviceData);

                currentDeviceData.setTimezone(TimeUtil.getTimeZone());

                currentDeviceData.setSupportWechat(WxSupportChecker.checkWxSupport());

                currentDeviceData.setAndroidApiLevel(Build.VERSION.SDK_INT);
//                loadInstallApps(currentDeviceData);
                loadInstallAppsInstead(currentDeviceData);
                DatagatherOaidManager.getInstance().init(DataGatherManager.getInstance().getContext(), new OAIDUtils.OnOAIDLoadCallBack() {
                    @Override
                    public void loadSuccess(String oaid) {
                        OAIDManager.getInstance().setIds(oaid);
                        if (oaid != null) {
                            currentDeviceData.setOaid(oaid);
                            currentDeviceData.setMd5Oaid(MD5Util.getMD5Code(oaid));
                        }
                        currentDeviceData.setVaid(DatagatherOaidManager.getInstance().getVAID());
                        //初始化中 应用列表和安装进行均不读取
                        deviceDataGatherListener.onDeviceDataGather(null
                                , currentDeviceData
                                , null
                                , null);
                    }

                    @Override
                    public void loadFailed() {

                    }
                },DataGatherManager.getInstance().isCanUseOaid());

            }
        });
    }

    public static void loadInstallApps(DeviceData deviceData) {
        if (localAppList != null && System.currentTimeMillis() - lastLoadAppListTime < 1000 * 60 * 60 * 2) {
            return;
        }


        PermissionUtils.getInstance().requestPermission(DataGatherManager.getInstance().getContext(), new PermissionUtils.PermissionRequestListener() {
            @Override
            public void onDenied() {

            }

            @Override
            public void onGranted(String[] permissions) {
                AsyncThreadPoolManager.getInstance().getThreadPool().execute(() -> {
//            List<String> appListBeans = new ArrayList<>();
//            PackageManager packageManager = DataGatherManager.getInstance().getContext().getPackageManager();
//            Intent intent = new Intent(Intent.ACTION_MAIN, null);
////        intent.addCategory(Intent.CATEGORY_LAUNCHER);
//            List<ResolveInfo> apps = packageManager.queryIntentActivities(intent, PackageManager.MATCH_ALL);
////            Log.e(TAG, "getInstallApp start");
//
//            for (int i = 0; i < apps.size(); i++) {
//                try {
//                    ResolveInfo info = apps.get(i);
//                    String packageName = info.activityInfo.packageName;//包名
//                    CharSequence cls = info.activityInfo.name;         //主Activity名称
//                    CharSequence name = info.activityInfo.loadLabel(packageManager);//app名
//                    ApplicationInfo applicationInfo = packageManager.getApplicationInfo(packageName, 0);
//                    String appDir = applicationInfo.sourceDir;
//                    //筛选非系统应用
//                    if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
//                        continue;
//                    }
//                    appListBeans.add(packageName);
//                    AdLogUtils.d("package = " + packageName + "--" + name);
////                    Log.e(TAG, "1->" + name + "----" + packageName + "----" + cls  + "----" + appDir);
//                } catch (Exception e) {
////                    Log.e(TAG, "error->" + e.toString());
//                }
//            }

//            Log.e(TAG, "getInstallApp end");

                    List<String> appListBeans = new ArrayList<>();
                    if (PermissionUtils.hasPermission(DataGatherManager.getInstance().getContext(), Manifest.permission.QUERY_ALL_PACKAGES)) {
                        PackageManager packageManager = DataGatherManager.getInstance().getContext().getPackageManager();
                        List<ApplicationInfo> installedApplications = packageManager.getInstalledApplications(PackageManager.GET_META_DATA);
                        for (ApplicationInfo applicationInfo : installedApplications) {
                            try {
                                PackageInfo packageInfo = packageManager.getPackageInfo(applicationInfo.packageName, PackageManager.GET_ACTIVITIES);
//                 获取app名称
//                String name = packageInfo.applicationInfo.loadLabel(packageManager).toString();
//                Drawable drawable = applicationInfo.loadIcon(packageManager);
//                Drawable drawable = context.getPackageManager().getApplicationIcon(packageInfo.packageName);
                                if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
                                    appListBeans.add(packageInfo.packageName);
                                }
                            } catch (PackageManager.NameNotFoundException e) {
                                e.printStackTrace();
                            }
                        }
                        int size = appListBeans.size();
                        deviceData.setInstallApps(appListBeans.toArray(new String[size]));
                        lastLoadAppListTime = System.currentTimeMillis();
                    }

                });
            }
        }, Manifest.permission.QUERY_ALL_PACKAGES);

    }

    /**
     * 测试 获取安装程序
     * Android 11 以上 配置 android.permission.QUERY_ALL_PACKAGES 权限
     * compileSdk 和 targetSdk 可以支持到 14
     * 不会触发系统的获取应用列表权限
     * 需要根据包名去重
     *
     */
    private static void loadInstallAppsInstead(DeviceData deviceData) {
        if (localAppList != null && System.currentTimeMillis() - lastLoadAppListTime < 1000 * 60 * 60 * 2) {
            return;
        }
        AsyncThreadPoolManager.getInstance().getThreadPool().execute(() -> {
            String TAG = "INSTALL_TTT";
            PackageManager packageManager = DataGatherManager.getInstance().getContext().getPackageManager();

            Intent intent = new Intent(Intent.ACTION_MAIN, null);
//        intent.addCategory(Intent.CATEGORY_LAUNCHER);
            List<ResolveInfo> apps = packageManager.queryIntentActivities(intent, 0);

            HashSet<String> appListBeans = new HashSet<>();
            for (int i = 0; i < apps.size(); i++) {
                try {
                    ResolveInfo info = apps.get(i);
                    String packageName = info.activityInfo.packageName;//包名
                    CharSequence cls = info.activityInfo.name;         //主Activity名称
                    CharSequence name = info.activityInfo.loadLabel(packageManager);//app名
                    ApplicationInfo applicationInfo = packageManager.getApplicationInfo(packageName, 0);
                    String appDir = applicationInfo.sourceDir;
                    if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
                        continue;
                    }
                    appListBeans.add(packageName);
//                    Log.e(TAG, "1->" + name + "----" + packageName + "----" + cls + "----" + appDir);
                } catch (Exception e) {
//                    Log.e(TAG, "error->" + e.toString());
                }
            }

//            Log.e(TAG, "getInstallApp end");

            int size = appListBeans.size();
            AdLogUtils.d("app size = " + size);
            deviceData.setInstallApps(appListBeans.toArray(new String[size]));
            lastLoadAppListTime = System.currentTimeMillis();
        });

    }


    /**
     * 手机蓝牙信息
     */
    private static void gatherBluetoothData(DeviceData deviceData) {
        CustomBluetoothInfo bluetoothInfo = BlueToothUtil.getBluetoothInfo();
    }

    /**
     * 手机与电池相关的数据
     */
    public static void gatherBatteryData(DeviceData deviceData) {
        deviceData.setBatteryPower(BatteryUtil.getBatteryLevel());
    }

    /**
     * 手机与电池相关的数据
     */
    public static void gatherCpuData(DeviceData deviceData) {
        deviceData.setCpuNumber(CpuUtil.getCpuNum());
        deviceData.setCpuFrequency(CpuUtil.getCpuFrequency());
    }

    /**
     * 收集地理位置信息和基站信息
     */
    public static void gatherLocationAndStationData(DeviceData deviceData) {
        try {
            LocationUtils locationUtils = LocationUtils.getInstance(DataGatherManager.getInstance().getContext());
            deviceData.setLatitude(Double.parseDouble(locationUtils.getLatitude()));
            deviceData.setLongitude(Double.parseDouble(locationUtils.getLongitude()));
        } catch (Exception e) {

        }
        Locale current = DataGatherManager.getInstance().getContext().getResources().getConfiguration().locale;
        deviceData.setCountry(current.getCountry());
//        deviceData.setAltitude(customLocation.getAltitude());

    }

    /**
     * 收集其他数据
     */
    private static void gatherOtherData(DeviceData deviceData) {
        deviceData.setUserAgent(DataCacheManager.getInstance().getUserAgent());
        Configuration configuration = DataGatherManager.getInstance().getContext().getResources().getConfiguration();
        if (configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            deviceData.setOrientation("LANDSCAPE");
        } else {
            deviceData.setOrientation("PORTRAIT");
        }
    }

    /**
     * 收集设备信息数据
     */
    private static void gatherPhoneStateData(DeviceData deviceData) {
        CustomPhoneState phoneState = PhoneStateUtil.getPhoneState();
        deviceData.setImsi(phoneState.getImsi());
        String imei = phoneState.getImei();
        deviceData.setImei(imei);
        deviceData.setMd5Imei(MD5Util.getMD5Code(imei));
//        deviceData.setMeid("");
//        deviceData.setIccid("");
        String androidId = phoneState.getAndroidId();
        deviceData.setAndroidId(androidId);
        deviceData.setMd5AndroidId(MD5Util.getMD5Code(androidId));
        deviceData.setDeviceType(phoneState.getDeviceType());
        ActivityManager.MemoryInfo info = new ActivityManager.MemoryInfo();
        ActivityManager manager = (ActivityManager) DataGatherManager.getInstance().getContext().getSystemService(Context.ACTIVITY_SERVICE);
        manager.getMemoryInfo(info);
        deviceData.setMemorySize(info.totalMem);

        StatFs statFs = new StatFs(Environment.getExternalStorageDirectory().getPath());
        long blockSize = statFs.getBlockSizeLong();
        long totalBlock = statFs.getBlockCountLong();
        deviceData.setDiskSize(totalBlock*blockSize);

        long bootTime = SystemClockUtil.getUpTime() / 1000;
        deviceData.setOsBootTime(bootTime);
        deviceData.setOsElapseTime(SystemClockUtil.getElapsedRealtime() / 1000);
    }

    /**
     * 收集网络相关数据
     */
    private static void gatherNetworkData(DeviceData deviceData) {
        deviceData.setNetwork(NetworkUtil.getCurrentNetType(""));
        deviceData.setIp(NetworkUtil.getHostIP());
        deviceData.setIpV6(NetworkUtil.getHostIPv6());
        String mac = NetworkUtil.getMacAddress();
        deviceData.setMac(mac);
        deviceData.setMacMD5(MD5Util.getMD5Code(mac));
    }

    /**
     * 收集展示信息（类似屏幕宽高、分辨率等）
     */
    private static void gatherDisplayData(DeviceData deviceData) {
        deviceData.setScreenWidth(DisplayUtil.getScreenWidth());
        deviceData.setScreenHeight(DisplayUtil.getScreenHeight());
        deviceData.setOsVersion(Build.VERSION.RELEASE);
        deviceData.setPpi(DisplayUtil.getPPi());
        deviceData.setInch(DisplayUtil.getScreenWidth() * DisplayUtil.getScreenHeight());
        deviceData.setVendor(Build.MANUFACTURER);
        deviceData.setModelNo(Build.MODEL);

    }

}
